<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\Role;
use Input;

class AdminController extends BaseController{
	
	public function getIndex(){
		return view('admin.index');
	}
	
	//返回DataTable
	public function getDatatable(){
        $dt=array();
        $orderby = isset( $_GET[ 'order'  ] ) ? $_GET[ 'columns' ][ $_GET[ 'order' ][ 0 ][ 'column' ] ][ 'name' ] : 'xz_admin.id';
    	$orderdir = isset( $_GET[ 'order'  ] ) ? $_GET[ 'order' ][ 0 ][ 'dir' ] : 'asc';
        $start = Input::get('start',0);//从多少开始
        $length = Input::get('length',10);//数据长度
        $search = $_GET['search']['value'];//搜索获取前台传过来的过滤条件

        $recordsTotal = Admin::with('role')->count();
        $where='1=1 ';
        if($search!=''){
        	$where.='and (username like "%'.$search.'%" or email like "%'.$search.'%" or phone like "%'.$search.'%" or fullname like "%'.$search.'%")';
        }
        $data = Admin::with('role')->whereRaw($where)->skip($start)->take($length)->orderBy($orderby,$orderdir)->get();
        $recordsFiltered=Admin::with('role')->whereRaw($where)->count();
        
        $datatable=array();
        $isrestpwdstr='';
        $iseditstr='';
        $isdelstr='';
        if (\Gate::check('chkaccess', 'App\Http\Controllers\AdminController@postResetpwd')) {
        	$isrestpwdstr='<button class="btn-white btn btn-xs" onclick="resetpwd($rerestpwdstr)">重置密码</button>';
        }
        if (\Gate::check('chkaccess', 'App\Http\Controllers\AdminController@getEdit')) {
         	$iseditstr='<button class="btn-white btn btn-xs" onclick="location.href=\'/admin/edit/$reeditstr\'">编辑</button>';
        }
        if (\Gate::check('chkaccess', 'App\Http\Controllers\AdminController@postDel')) {
        	$isdelstr='<button class="btn-white btn btn-xs" onclick="singledel(\'/admin/del\',$redelstr);">删除</button>';
        }
        foreach ($data as $item) {
        	$status_at=$item->status_at==1?'<span class="label label-primary">启用</span>':'<span class="label label-danger">禁用</span>';
        	$gender=$item->gender==1?'男':'女';
        	$obj=array('<input type="checkbox" name="chk" value='.$item->id.' />',$item->id,$item->username,$item->fullname,$item->email,$item->phone,$gender,$item->role->name,$item->created_at->format('Y-m-d H:i:s'),$item->updated_at->format('Y-m-d H:i:s'),$status_at,str_replace('$rerestpwdstr',$item->id,$isrestpwdstr).str_replace('$reeditstr',$item->id,$iseditstr).str_replace('$redelstr',$item->id,$isdelstr));
            array_push($datatable,$obj);
        }
        $dt['draw']=intval(Input::get('draw',0));
        $dt['data']=$datatable;
        $dt['recordsTotal']=$recordsTotal;
        $dt['recordsFiltered']=$recordsFiltered;
        // $dt['error']='暂时没有数据';
        echo json_encode($dt);     
    }

	public function getAdd(){
		$roles=Role::where('status_at',1)->get();
		return view('admin.add')->with('roles',$roles);
	}

	public function postAdd(){
		\Input::merge(array_map('trim', \Input::all()));
		$username=Input::get('username');
		$admin = new Admin;
		$isExist=Admin::where('username',$username)->first();
		if($isExist){
			return redirect('tooltip/failure')->with(['redirectway'=>'用户名已存在！','redirecturl'=>'/admin/index']);
		}
		$admin->username = $username;
		$email=Input::get('email');
		$isExist=Admin::where('email',$email)->first();
		if($isExist){
			return redirect('tooltip/failure')->with(['redirectway'=>'Email已存在！','redirecturl'=>'/admin/index']);
		}
		$admin->email = $email;
		$phone=Input::get('phone');
		$isExist=Admin::where('phone',$phone)->first();
		if($isExist){
			return redirect('tooltip/failure')->with(['redirectway'=>'手机已存在！','redirecturl'=>'/admin/index']);
		}
		$admin->phone = $phone;
		$admin->fullname =Input::get('fullname');
		$admin->gender = Input::get('gender');
		$admin->password = bcrypt(config('site.dftpwd'));
		$admin->role_id =Input::get('role_id');
		$res=$admin->save();
		if($res){
			return redirect('tooltip/success')->with(['redirectway'=>'添加成功！','redirecturl'=>'/admin/index']);
		}else{
			return redirect('tooltip/failure')->with(['redirectway'=>'添加失败！','redirecturl'=>'/admin/index']);
		}
	}
	
	public function getEdit($id){
		$admin = Admin::find($id);
		$info['admin']=$admin;
		$info['roles']=Role::where('status_at',1)->get();
		return view('admin.edit')->with('info',$info);
	}

	public function postEdit(){
		\Input::merge(array_map('trim', \Input::all()));
		$admin = Admin::find(Input::get('id'));
		$username=Input::get('username');
		$isExist=Admin::where('id','!=',$admin->id)->where('username',$username)->first();
		if($isExist){
			return redirect('tooltip/failure')->with(['redirectway'=>'用户名已存在！','redirecturl'=>'/admin/index']);
		}
		$admin->username = $username;
		$email=Input::get('email');
		$isExist=Admin::where('id','!=',$admin->id)->where('email',$email)->first();
		if($isExist){
			return redirect('tooltip/failure')->with(['redirectway'=>'Email已存在！','redirecturl'=>'/admin/index']);
		}
		$admin->email = $email;
		$phone=Input::get('phone');
		$isExist=Admin::where('id','!=',$admin->id)->where('phone',$phone)->first();
		if($isExist){
			return redirect('tooltip/failure')->with(['redirectway'=>'手机已存在！','redirecturl'=>'/admin/index']);
		}
		$admin->phone = $phone;
		$admin->fullname =Input::get('fullname');
		$admin->gender = Input::get('gender');
		$admin->role_id =Input::get('role_id');
		$res=$admin->save();
		if($res){
			return redirect('tooltip/success')->with(['redirectway'=>'修改成功！','redirecturl'=>'/admin/index']);
		}else{
			return redirect('tooltip/failure')->with(['redirectway'=>'修改失败！','redirecturl'=>'/admin/index']);
		}
	}

	public function postDel(){
		$res=Admin::destroy(Input::get('data'));
		if($res){
			die('1');
		}
		else{
			die('0');
		}
	}

	public function postResetpwd(){
		$id=Input::get('data');
		$admin = Admin::find($id);
		$admin->password = bcrypt(config('site.dftpwd'));
		$res=$admin->save();
		if($res){
			die('1');
		}
		else{
			die('0');
		}
	}

	//获取jstree树形结构（添加）
	private function getTreeview($data,$pid=0)
    {
        $tree = array();
        foreach($data as $k => $v)
        {
            if($v['pid'] == $pid){
            	$tmparr = array();
            	$tmparr['id']=$v['id'];
                $tmparr['text']=$v['name'];
                $tmparr['state']=array('opened'=>true);
                $tmparr['level']=$v['level'];
                $tmparr['children'] =$this->getTreeview($data,$v['id']);
                $tree[] = $tmparr;
                unset($data[$k]);
           }
        }
        return $tree;
    }

    //获取jstree树形结构（编辑）
	private function getTreeviewe($data,$pid=0,$dptid)
    {
        $tree = array();
        foreach($data as $k => $v)
        {
            if($v['pid'] == $pid){
            	$tmparr = array();
            	$tmparr['id']=$v['id'];
                $tmparr['text']=$v['name'];
                $tmparr['state']['opened']=true;
                if($dptid==$v['id']){
                	$tmparr['state']['selected']=true;
                }
                $tmparr['children'] =$this->getTreeviewe($data,$v['id'],$dptid);
                $tree[] = $tmparr;
                unset($data[$k]);
           }
        }
        return $tree;
    }



}
